package cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1.system;

import cn.com.sparkle.paxos.Context;
import cn.com.sparkle.paxos.event.events.NodeStateChangeEvent;
import cn.com.sparkle.paxos.model.ElectionId;
import cn.com.sparkle.paxos.net.client.NetNode;
import cn.com.sparkle.paxos.net.client.system.SystemNetNode;
import cn.com.sparkle.paxos.net.netlayer.PaxosSession;
import cn.com.sparkle.paxos.net.netlayer.PaxosSessionKeys;
import cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1.AbstractProtocolV0_0_1Processor;
import cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1.PaxosMessages.ActiveHeartBeatRequest;
import cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1.PaxosMessages.MessagePackage;
import cn.com.sparkle.paxos.net.protocolprocessor.v0_0_1.PaxosMessages.SenatorHeartBeatResponse;
import cn.com.sparkle.paxos.state.NodeState;

public class ActiveHeartProcessor extends AbstractProtocolV0_0_1Processor {

	private Context context;

	public ActiveHeartProcessor(Context context) {
		this.context = context;
	}

	@Override
	public boolean receive(MessagePackage t, PaxosSession session) {
		if (t.hasActiveHeartBeatRequest()) {
			ActiveHeartBeatRequest request = t.getActiveHeartBeatRequest();
			NetNode node = (NetNode) session.get(PaxosSessionKeys.NET_NODE_KEY);
			SenatorHeartBeatResponse heart = request.getHeartBeatResponse();

			NodeState nodeState = new NodeState(request.getAddress());
			nodeState.setLastBeatHeatTime(System.currentTimeMillis());
			nodeState.setMasterConnected(heart.getIsMasterConnected());
			nodeState.setLastElectionId(new ElectionId(heart.getElectionAddress(), heart.getElectionId(), heart.getElectionVersion()));
			nodeState.setLastCanExecuteInstanceId(heart.getLastCanExecuteInstanceId());
			nodeState.setInit(heart.getIsInited());
			nodeState.setConnected(false);
			nodeState.setUpToDate(heart.getIsUpToDate());
			nodeState.setMasterDistance(heart.getMasterDistance());
			nodeState.setConnectedValidNode(heart.getConnectedValidNodesList());

			SystemNetNode upLevelNode = context.getcState().getRouteManage().lookupUpLevelNode();
			if (upLevelNode != null) {
				upLevelNode.sendActiveHeartBeat(nodeState);
			}

			NodeStateChangeEvent.doActiveBeartHeartEvent(context.getEventsManager(), node, nodeState);
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void onConnect(PaxosSession session) {
	}

	@Override
	public void onDisConnect(PaxosSession session) {
	}

}
